import {
    Box,
    Button,
    CircularProgress,
    Dialog,
    DialogContent,
    Grid,
    Slide,
    Table,
    TableBody,
    TableCell,
    TableHead,
    TableRow,
    Typography
} from '@mui/material';
import { TransitionProps } from '@mui/material/transitions';
import MainLayout from 'components/HOCs/main-layout';
import GFSTable from 'components/shared/tables/gfs-table';
import TransactionStatus from 'components/shared/tables/status';
import { format } from 'date-fns';
import NumberTool from 'libs/number-tool';
import { useRouter } from 'next/router';
import { forwardRef, ReactElement, Ref, useEffect, useState } from 'react';

import TransactionManager from '../../../api/transaction/transaction-manager';
import { getStatusName } from '../../../constants/status';
import { useInfiniteScroll } from '../../../hooks/infinitive-scroll';
import { useLoadTransactions } from '../../../hooks/transaction-load-more-';

const Transition = forwardRef(function Transition(
    props: TransitionProps & {
        children: ReactElement<any, any>;
    },
    ref: Ref<unknown>
) {
    return <Slide direction="up" ref={ref} {...props} />;
});

const TransactionPage = () => {
    const router = useRouter();
    const [disbursementID, setDisbursementID] = useState(null);
    const [downloadLoading, setDownloadLoading] = useState(false);

    const { loading, disbursement, items, hasNextPage, error, loadMore } =
        useLoadTransactions(disbursementID);

    const [pageLoading, setPageLoading] = useState(true);

    const [sentryRef] = useInfiniteScroll({
        loading,
        hasNextPage,
        onLoadMore: loadMore,
        disabled: !!error,
        rootMargin: '0px 0px 400px 0px'
    });

    useEffect(() => {
        if (!router.isReady) return;
        const { id } = router.query;
        setDisbursementID(id);
    }, [router.isReady]);

    useEffect(() => {
        const load = async () => {
            await loadMore();
            setPageLoading(false);
        };

        if (disbursementID) {
            load().then();
        }
    }, [disbursementID]);

    console.log('items', items);

    const downloadCSV = async () => {
        setDownloadLoading(true);
        try {
            const transactions = await TransactionManager.getAll(disbursementID);

            let content = 'data:text/csv;charset=utf-8,';
            content += 'id,name,amount,fee,wallet_address,email,status,transaction_hash\r\n';

            transactions.forEach((transaction) => {
                const array = [
                    transaction.id,
                    transaction.name,
                    transaction.amount + ' ' + disbursement?.currency,
                    transaction.gasFee?.amount + ' ' + transaction.gasFee?.token,
                    transaction.walletAddress,
                    transaction.email,
                    getStatusName(transaction.status),
                    transaction.transactionHash
                ];

                const row = array.join(',');
                content += row + '\r\n';
            });

            const encodedUri = encodeURI(content);
            const link = document.createElement('a');
            link.setAttribute('href', encodedUri);
            link.setAttribute('download', 'GFS Disbursement.csv');
            document.body.appendChild(link);
            link.click();
        } catch (e) {
            console.log('error', e);
        }
        setDownloadLoading(false);
    };

    return (
        <MainLayout>
            <Box sx={{ pl: 6, pr: 6 }}>
                <Typography variant="h2" color="white" sx={{ pb: 3 }}>
                    Transactions
                </Typography>

                {pageLoading ? (
                    <Typography variant="h6" color="white">
                        Loading...
                    </Typography>
                ) : (
                    <Box sx={{ pb: 4 }}>
                        <Grid
                            sx={{ pt: 2, pb: 2 }}
                            container
                            justifyContent="space-between"
                            spacing={2}
                        >
                            <Grid item xs={8}>
                                <Typography variant="h4" color="white">
                                    {disbursement ? disbursement.title : ''}
                                </Typography>
                            </Grid>
                            <Grid item xs={4} textAlign="right">
                                {items && items.length > 0 && (
                                    <Button
                                        variant="contained"
                                        component="label"
                                        onClick={downloadCSV}
                                        sx={{
                                            background: '#5148fc',
                                            '&:hover': {
                                                background: '#5148fc',
                                                color: '#ffffff'
                                            }
                                        }}
                                    >
                                        Download CSV
                                    </Button>
                                )}
                            </Grid>
                        </Grid>

                        {!error ? (
                            <Box>
                                <GFSTable>
                                    <Table sx={{ minWidth: 650 }} aria-label="simple table">
                                        <TableHead>
                                            <TableRow>
                                                <TableCell align="center" colSpan={2}>
                                                    Date
                                                </TableCell>
                                                <TableCell align="center">Activity</TableCell>
                                                <TableCell align="center">Status</TableCell>
                                                <TableCell align="center">
                                                    Amount Disbursed
                                                </TableCell>
                                            </TableRow>
                                        </TableHead>
                                        <TableBody>
                                            {items?.length > 0 &&
                                                items.map((row) => (
                                                    <TableRow
                                                        key={row.name}
                                                        sx={{
                                                            '&:last-child td, &:last-child th': {
                                                                border: 0
                                                            }
                                                        }}
                                                        hover={true}
                                                    >
                                                        <TableCell align="center">
                                                            {format(
                                                                row.timestamp,
                                                                'MM / dd / yyyy'
                                                            )}
                                                        </TableCell>
                                                        <TableCell align="center">
                                                            {format(
                                                                row.timestamp,
                                                                "hh:mm aaaaa'm'"
                                                            )}
                                                        </TableCell>
                                                        <TableCell align="center">
                                                            <b>Disbursed</b> to <b>{row.name}</b>
                                                        </TableCell>
                                                        <TableCell align="center">
                                                            <TransactionStatus
                                                                status={row.status}
                                                            />
                                                        </TableCell>
                                                        <TableCell align="center">
                                                            {NumberTool.format(row.amount)} SLP
                                                        </TableCell>
                                                    </TableRow>
                                                ))}
                                        </TableBody>
                                    </Table>
                                </GFSTable>
                                {(loading || hasNextPage) && (
                                    <Box
                                        display="flex"
                                        justifyContent="center"
                                        alignItems="center"
                                        sx={{ pt: 4 }}
                                    >
                                        <CircularProgress
                                            ref={sentryRef}
                                            sx={{ color: '#ffffff' }}
                                        />
                                    </Box>
                                )}
                            </Box>
                        ) : (
                            <Typography className="top-20">No transactions yet...</Typography>
                        )}
                    </Box>
                )}
            </Box>

            <Dialog
                open={downloadLoading}
                TransitionComponent={Transition}
                keepMounted
                aria-describedby="alert-dialog-slide-description"
            >
                <style jsx global>{`
                    .dialog-background {
                        background: linear-gradient(
                            278.2deg,
                            rgba(56, 175, 254, 0.95) -29.02%,
                            rgba(74, 17, 145, 0.95) 113.46%
                        );
                    }
                `}</style>
                <div className={'dialog-background'}>
                    <DialogContent>
                        <Box
                            sx={{ p: 10 }}
                            display="flex"
                            justifyContent="center"
                            alignItems="center"
                        >
                            <Typography variant={'h5'} color="white">
                                Processing
                            </Typography>
                            <CircularProgress sx={{ ml: 2, color: '#ffffff' }} />
                        </Box>
                    </DialogContent>
                </div>
            </Dialog>
        </MainLayout>
    );
};

export default TransactionPage;
